package option

import (
	"context"
	"strings"
	"time"

	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/product/rpc/internal/svc"
	"mall/service/product/rpc/internal/utils/errorhandler"
	"mall/service/product/rpc/types/product"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateAttributeOptionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateAttributeOptionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateAttributeOptionLogic {
	return &UpdateAttributeOptionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateAttributeOptionLogic) UpdateAttributeOption(in *product.AttributeOptionInfo) (*product.BaseResp, error) {
	// logx.Infof("UpdateAttribute : %+v ", in)

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(in.Ids) > 0 && in.Status != nil { // 批量修改状态
		now := time.Now()
		for _, id := range in.Ids {
			if id > 0 {
				opt, err := l.svcCtx.Attribute.FindOption(l.ctx, tx, id)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}

				opt.Status = uint8(*in.Status)
				opt.UpdatedAt = now
				err = l.svcCtx.Attribute.UpdateOption(l.ctx, tx, opt)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}
			}
		}

		tx.Commit()

		return &product.BaseResp{
			Msg: i18n.UpdateSuccess,
		}, nil
	}

	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	id := *in.Id

	if in.Name != nil && len(strings.TrimSpace(*in.Name)) == 0 {
		return nil, errorx.NewInvalidArgumentError("attribute.optionNameRequired")
	}

	opt, err := l.svcCtx.Attribute.FindOption(l.ctx, tx, id)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if in.Name != nil {
		opt.Name = strings.TrimSpace(*in.Name)
	}

	if in.Slug != nil { // 允许为空，不管长度
		opt.Slug = strings.TrimSpace(*in.Slug)
	}
	if in.Sort != nil {
		opt.Sort = uint16(*in.Sort)
	}
	if in.Status != nil {
		opt.Status = uint8(*in.Status)
	}
	opt.UpdatedAt = time.Now()

	err = l.svcCtx.Attribute.UpdateOption(l.ctx, tx, opt)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &product.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
